package edu.itla.medifacil.persistence.managers;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import edu.itla.medifacil.persistence.entities.Appointment;

public class AppointmentManager {
	private EntityManager em = null;
	
	public AppointmentManager(){
		this.em = Persistence.createEntityManagerFactory("MediFacil").createEntityManager();
	}
	
	public Appointment save( Map<String, String> parameters ){
		Appointment appointment = new Appointment();
		PersonManager personManager = new PersonManager();
		
		int doctorId = Integer.parseInt(parameters.get("doctorId"));
		int patientId = Integer.parseInt( parameters.get("patientId") );
		String issue = parameters.get("issue");
		String [] dateMetadata = parameters.get("date").split("-");
		int year = Integer.parseInt(dateMetadata[0]);
		int month = Integer.parseInt(dateMetadata[1]);
		int day = Integer.parseInt(dateMetadata[2]);
		int hours = Integer.parseInt(dateMetadata[3]);
		int minutes = Integer.parseInt(dateMetadata[4]);
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month, day, hours, minutes);
		Date date = calendar.getTime();
		
		if( parameters.get("id") != null && parameters.get("id").trim().length() > 0 )
			appointment = this.find( Integer.parseInt(parameters.get("id")) );
		
		appointment.setDate(date);
		appointment.setIssue(issue);
		appointment.setDoctor( personManager.find(doctorId) );
		appointment.setPatient( personManager.find(patientId) );
		
		em.getTransaction().begin();
		em.persist(appointment);
		em.getTransaction().commit();
		
		return appointment;
	}
	
	public void delete( int appointmentId ){
		em.getTransaction().begin();
		em.createQuery("DELETE FROM Appointment WHERE id="+appointmentId).executeUpdate();
		em.getTransaction().commit();
	}

	public Appointment find( int appointmentId ){
		em.clear();
		return em.find( Appointment.class, appointmentId);
	}
	
	@SuppressWarnings("unchecked")
	public List<Appointment> findAll(){
		return (List<Appointment>) em.createQuery( "SELECT a FROM Appointment a").getResultList();
	}
}
